import Vue from 'vue'
import Vuex from 'vuex'
import http from '@/util/http';
import createPersistedState from "vuex-persistedstate";

Vue.use(Vuex)

export default new Vuex.Store({
  // 将devtools状态也存一份在localStorage中，实现持久化
  plugins: [createPersistedState({
    reducer: (state) => {   // 设置需要存的数据
      return {
        cityId: state.cityId,
        cityName: state.cityName,
        cinemaList: state.cinemaList,
        filmName: state.filmName,
        filmId: state.filmId,
        date: state.date,
        poster: state.poster,
        index: state.index,
        first: state.first
      }
    }
  })],

  state: {
    cityName: '广州',
    cityId: '440100',
    cinemaList: [],
    isTabbarShow: true,
    filmName: '',
    filmId: '',
    date: '',
    poster: '',
    index: 0,
    first: 0,
  },
  // 计算属性
  getters: {
    topList(state) {
      return state.cinemaList.filter((item, index) => index < 5)
    }
  },
  // 统一管理状态，被devtools 记录状态修改
  // 只支持同步
  mutations: {
    changeCityName(state, cityName) {
      state.cityName = cityName
    },
    changeCityId(state, cityId) {
      state.cityId = cityId
    },
    changeCinemaData(state, data) {
      state.cinemaList = data
    },
    changeFilmName(state, filmName) {
      state.filmName = filmName
    },
    changeFilmId(state, filmId) {
      state.filmId = filmId
    },
    changeDate(state, date) {
      state.date = date
    },
    changePoster(state, poster) {
      state.poster = poster
    },
    changeIndex(state, index) {
      state.index = index
    },
    // 用于判断电影影院购票界面是否是第一次发起电影的数据请求
    changeFirst(state, first) {
      state.first = first
    },
    clearCinemaData(state) {
      state.cinemaList = []
    },
    // vuex 管理底部选项卡显示状态
    show(state) {
      state.isTabbarShow = true
    },
    hide(state) {
      state.isTabbarShow = false
    }
  },
// 支持异步和同步
  actions: {
    // 方案1. 直接拿store的state数据
    // getCinemaData(store){
    //   http.httpForCinema(store.state.cityId).then(res => {

    // 方案2. 传参进来
    getCinemaData(store, cityId) {
      return http.httpForCinema(cityId).then(res => {
        // console.log(res.data.data.cinemas)
        store.commit('changeCinemaData', res.data.data.cinemas)
      })
    }
  }
  ,
  modules: {}
})

// vuex 管理保存公共状态，（分散在各个组件内的状态，统一管理）

// vuex 默认管理在内存，一刷新，公共状态就丢失
// vuex -- 持久化-

/*   异步
  vuex 项目应用：两个页面的数据相同，有一个页面的数据包含其他页面需要的数据
  1. 非父子的通信
  2. 后端数据的缓存快照，减少重复请求数据，减轻服务器压力，提高用户体验
 */
